package znet

import (
	"gitee.com/jiangjiali/z-tcp/utils"
	"gitee.com/jiangjiali/z-tcp/ziface"
	"sync"
	"time"
)

type Limier struct {
	sync.Mutex
	Interval time.Duration
	MaxCount int
	ReqCount int
}

func NewLimiter() ziface.ILimiter {
	var interval = 1 * time.Second //1秒
	var maxCnt = utils.GlobalObject.Limiter
	limiter := &Limier{
		Interval: interval,
		MaxCount: maxCnt,
	}

	go func() {
		ticker := time.NewTicker(interval)
		for {
			<-ticker.C
			limiter.Lock()
			//log.Println("限制器-重置计数")
			limiter.ReqCount = 0
			limiter.Unlock()
		}
	}()

	return limiter
}

// Increase 请求记数增加1
func (l *Limier) Increase() {
	l.Lock()
	defer l.Unlock()

	l.ReqCount += 1
}

func (l *Limier) IsAvailable() bool {
	l.Lock()
	defer l.Unlock()

	return l.ReqCount < l.MaxCount
}
